//
//  LIUDetailViewController.m
//  EasyNotes
//
//  Created by 劉裕 on 27/5/2016.
//  Copyright © 2016年 劉裕. All rights reserved.
//

#import "LIUDetailViewController.h"
#import "LIUListCell.h"
#import "LIUNote.h"
#import "LIUWebView.h"
#import <Masonry/Masonry.h>
#import "LIUTextView.h"
#import "RFKeyboardToolbar.h"
#import "LIUWriteToFileUnit.h"

@interface LIUDetailViewController () <YYTextViewDelegate, UINavigationControllerDelegate, UIImagePickerControllerDelegate>

@property (nonatomic, strong) LIUNote *note;
@property (nonatomic, weak) UIWebView *webView;
@property (nonatomic, weak) LIUTextView *markDownTextView;
@end

@implementation LIUDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
//    if ([self respondsToSelector:@selector(edgesForExtendedLayout)]) {
//        self.edgesForExtendedLayout = UIRectEdgeNone;
//    }
    
    [self setupView];
    [self loadHtml];
}

//- (void)viewWillDisappear:(BOOL)animated {
//    [super viewWillDisappear:animated];
//    self.navigationController.navigationBarHidden = NO;
//}

#pragma mark - Private Methods

- (void)loadHtml {
    LIUNote *note = self.cell.viewModel;
    self.note = note;
    NSString *idStr = note.idStr;
    NSString *file = [idStr stringByAppendingString:@".html"];
    NSString *htmlPath = [[[NSString.document stringByAppendingPathComponent:@"HTML"] stringByAppendingPathComponent:idStr] stringByAppendingPathComponent:file];
    
    NSURL *htmlUrl = [NSURL URLWithString:htmlPath];
    NSURLRequest *request = [NSURLRequest requestWithURL:htmlUrl];
    [self.webView loadRequest:request];
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"edit", nil) style:UIBarButtonItemStylePlain target:self action:@selector(editItemClick)];
}

- (void)setupView {
    NSArray *toolbarBtns = [self getToolbarBtn];
    
    // 导航栏遮盖问题解决
    self.edgesForExtendedLayout = UIRectEdgeNone;
    self.extendedLayoutIncludesOpaqueBars = NO;
    self.modalPresentationCapturesStatusBarAppearance = NO;
    
    WS(ws)
    LIUWebView *webview = [LIUWebView new];
    [self.view addSubview:webview];
    self.webView = webview;
    [webview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.bottom.right.equalTo(ws.view).offset(0);
    }];
    
    LIUTextView *markDownTextView = [LIUTextView new];
    markDownTextView.delegate = self;
    markDownTextView.inputAccessoryView = [RFKeyboardToolbar toolbarWithButtons:toolbarBtns];
    [self.view addSubview:markDownTextView];
    self.markDownTextView = markDownTextView;
    [markDownTextView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.bottom.right.equalTo(ws.view);
    }];
    markDownTextView.hidden = YES;
}

- (void)editItemClick {
    [self setupEditView];
}

- (void)setupEditView {
    self.webView.hidden = YES;
    self.markDownTextView.hidden = NO;
    NSString *str = self.note.noteContent;
    self.markDownTextView.text = str;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.6 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self.markDownTextView becomeFirstResponder];
    });
}

- (void)textViewDidBeginEditing:(YYTextView *)textView {
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"save", nil) style:UIBarButtonItemStyleDone target:self action:@selector(save)];
    self.navigationItem.rightBarButtonItem.enabled = NO;
}

- (void)textViewDidEndEditing:(YYTextView *)textView {
    self.navigationItem.rightBarButtonItem.enabled = NO;
}

- (void)textViewDidChange:(YYTextView *)textView {
    self.navigationItem.rightBarButtonItem.enabled = textView.hasText;
}

/**
 *  保存或更新笔记
 */
- (void)save {
    NSError *error = NULL;
    [self.markDownTextView endEditing:YES];
    RLMRealm *realm = [RLMRealm defaultRealm];
    [realm beginWriteTransaction];
    if (self.note.idStr.length == 36) {
        LIUNote *newNote = self.note;
        NSString *contentText = self.markDownTextView.text;
        newNote.noteTitle = [LIUWriteToFileUnit getTitle:contentText];
        newNote.noteContent = contentText;
        [LIUNote createOrUpdateInRealm:realm withValue:newNote];
        [realm commitWriteTransaction:&error];
        [LIUWriteToFileUnit writeToFile:newNote];
    } else {
        LIUNote *note = [[LIUNote alloc] init];
        note.idStr = [[NSUUID UUID] UUIDString];
        NSString *contentText = self.markDownTextView.text;
        NSString *title = [LIUWriteToFileUnit getTitle:contentText];
        
        note.noteTitle = title;
        note.noteContent = contentText;
        note.noteCreateDate = [NSDate new];
        [realm addObject:note];
        [realm commitWriteTransaction:&error];
        [LIUWriteToFileUnit writeToFile:note];
        self.note = note;
    }
    
    self.webView.hidden = NO;
    self.markDownTextView.hidden = YES;
    [self loadHtml];
}

- (void)alertController {
    UIColor *red = LIUColor(217, 98, 84, 1.0);
    WS(ws)
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"网址" message:@"输入网址" preferredStyle:UIAlertControllerStyleAlert];
    [alert addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        textField.placeholder = @"名称";
    }];
    [alert addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        textField.placeholder = @"网址";
        textField.text = @"https://";
    }];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"cancel", nil) style:UIAlertActionStyleCancel handler:nil];
    UIAlertAction *confirmAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"confirm", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        UITextField *websiteName = alert.textFields.firstObject;
        UITextField *websiteAddress = alert.textFields.lastObject;
        websiteName.tintColor = red;
        websiteAddress.tintColor = red;
        //        [行内链接](http://www.limitblog.top/)
        NSString *str = [NSString stringWithFormat:@"[%@](%@)", websiteName.text, websiteAddress.text];
        [ws.markDownTextView insertText:str];
    }];
    
    [cancelAction setValue:red forKey:@"titleTextColor"];
    [confirmAction setValue:red forKey:@"titleTextColor"];
    
    [alert addAction:cancelAction];
    [alert addAction:confirmAction];
    [self presentViewController:alert animated:YES completion:nil];
}

- (NSArray<RFToolbarButton *> *)getToolbarBtn {
    WS(ws)
    RFToolbarButton *title = [RFToolbarButton buttonWithTitle:@"#" andEventHandler:^{
        [ws.markDownTextView insertText:@"#"];
    } forControlEvents:UIControlEventTouchUpInside];
    RFToolbarButton *asterisk = [RFToolbarButton buttonWithTitle:@"*" andEventHandler:^{
        [ws.markDownTextView insertText:@"*"];
    } forControlEvents:UIControlEventTouchUpInside];
    RFToolbarButton *waveline = [RFToolbarButton buttonWithTitle:@"~" andEventHandler:^{
        [ws.markDownTextView insertText:@"~"];
    } forControlEvents:UIControlEventTouchUpInside];
    RFToolbarButton *section = [RFToolbarButton buttonWithTitle:@">" andEventHandler:^{
        [ws.markDownTextView insertText:@">"];
    } forControlEvents:UIControlEventTouchUpInside];
    RFToolbarButton *code = [RFToolbarButton buttonWithTitle:@"`" andEventHandler:^{
        [ws.markDownTextView insertText:@"`"];
    } forControlEvents:UIControlEventTouchUpInside];
    RFToolbarButton *cutline = [RFToolbarButton buttonWithTitle:@"-" andEventHandler:^{
        [ws.markDownTextView insertText:@"-"];
    } forControlEvents:UIControlEventTouchUpInside];
    RFToolbarButton *photo = [RFToolbarButton buttonWithTitle:@"img" andEventHandler:^{
        [ws photoPickerClick];
    } forControlEvents:UIControlEventTouchUpInside];
    RFToolbarButton *website = [RFToolbarButton buttonWithTitle:@"www." andEventHandler:^{
        [ws alertController];
    } forControlEvents:UIControlEventTouchUpInside];
    return @[title, asterisk, waveline, section, code, cutline, photo, website];
}

- (void)photoPickerClick {
    [self openImagePickerController:UIImagePickerControllerSourceTypePhotoLibrary];
}
- (void)openImagePickerController:(UIImagePickerControllerSourceType)type {
    if (![UIImagePickerController isSourceTypeAvailable:type]) return;
    UIImagePickerController *pickerCtrl = [[UIImagePickerController alloc] init];
    pickerCtrl.sourceType = type;
    pickerCtrl.delegate = self;
    pickerCtrl.allowsEditing = YES;
    [self presentViewController:pickerCtrl animated:YES completion:nil];
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
    
    void (^insertImage)(NSString *) = ^void(NSString *idStr) {
        NSString *imageName = [[NSString dateString] stringByAppendingPathExtension:@"png"];
        NSString *path = [[NSString.document stringByAppendingPathComponent:@"HTML"] stringByAppendingPathComponent:idStr];
        
        NSString *type = [info objectForKey:UIImagePickerControllerMediaType];
        if ([type isEqualToString:@"public.image"]) {
            UIImage *pickedImage = info[UIImagePickerControllerOriginalImage];
            NSData *data = nil;
            if (UIImagePNGRepresentation(pickedImage) == nil) {
                data = UIImageJPEGRepresentation(pickedImage, 0.5);
            } else {
                data = UIImagePNGRepresentation(pickedImage);
            }
            NSFileManager *mgr = [NSFileManager defaultManager];
            if ([mgr fileExistsAtPath:path]) {
                [mgr createFileAtPath:[path stringByAppendingPathComponent:imageName] contents:data attributes:nil];
            } else {
                [mgr createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:nil];
                [mgr createFileAtPath:[path stringByAppendingPathComponent:imageName] contents:data attributes:nil];
            }
        }
        NSString *title = NSLocalizedString(@"altTitle", nil);
        NSString *imageStr = [NSString stringWithFormat:@"![%@](%@)", title, imageName];
        [picker dismissViewControllerAnimated:YES completion:^{
            [self.markDownTextView insertText:imageStr];
        }];
    };
    
    if (self.note.idStr.length == 36) {
        NSString *idStr = self.note.idStr;
        insertImage(idStr);
    } else {
        LIUNote *note = [[LIUNote alloc] init];
        note.idStr = [[NSUUID UUID] UUIDString];
        NSString *idStr = note.idStr;
        insertImage(idStr);
        self.note = note;
    }
}

//- (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset {
//    [self.navigationController setNavigationBarHidden:(velocity.y > 0) animated:YES];
//}


@end
